package com.seata.demo.interceptor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.collections.CaseInsensitiveKeyMap;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;

/**
* @comments
* @author  zg
* @date 2021年2月16日
*/
@Slf4j
@Component
public class RequestHeaderInterceptor implements RequestInterceptor{

    @Override
    public void apply(RequestTemplate template) {
        log.info("RequestHeaderInterceptor......");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                Map<String, Collection<String>> resolvedHeaders = new CaseInsensitiveKeyMap<>();
                resolvedHeaders.putAll(template.headers());

                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    if (!resolvedHeaders.containsKey(name)) {
                        String values = request.getHeader(name);
                        List<String> headers = new ArrayList<String>();
                        headers.addAll(Arrays.asList(values));
                        resolvedHeaders.put(name, headers);
                    }
                }
                template.headers(null);
                template.headers(resolvedHeaders);
            }
        }
        /*Map<String, Collection<String>> headers = template.headers();
        if(headers != null){
            Collection<String> values = headers.getOrDefault(SeataConstants.TRANSACTION_MODE_HEADER, null);
            if (values == null) {
                values = headers.getOrDefault(SeataConstants.TRANSACTION_MODE_HEADER.toLowerCase(), null);
            }
            if(values!=null && values.contains("TCC")){
                seataTransactionATMode = false;
            }
        }*/
        String xid = RootContext.getXID();
        if (StringUtils.isNotBlank(xid)) {
            template.header(RootContext.KEY_XID, xid);
        }
    }
    

}
